package com.example.chamberlainserver.Service.impl;

import com.example.chamberlainserver.Entry.MaterialCategory;
import com.example.chamberlainserver.Service.MaterialCategoryService;
import com.example.chamberlainserver.mapper.MaterialCategoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 物资分类服务实现类
 */
@Service
public class MaterialCategoryServiceImpl implements MaterialCategoryService {

    @Autowired
    private MaterialCategoryMapper materialCategoryMapper;

    @Override
    @Transactional
    public boolean addCategory(MaterialCategory category) {
        // 检查分类名称是否已存在
        MaterialCategory existingCategory = materialCategoryMapper.getCategoryByName(category.getName());
        if (existingCategory != null) {
            throw new IllegalArgumentException("分类名称已存在");
        }
        
        // 如果有父分类，检查父分类是否存在
        if (category.getParentId() != null) {
            MaterialCategory parentCategory = materialCategoryMapper.getCategoryById(category.getParentId());
            if (parentCategory == null) {
                throw new IllegalArgumentException("父分类不存在");
            }
        }
        
        // 设置默认的排序序号，避免sortOrder为null
        if (category.getSortOrder() == null) {
            category.setSortOrder(0); // 设置默认值为0
        }
        
        return materialCategoryMapper.insertCategory(category) > 0;
    }

    @Override
    @Transactional
    public boolean updateCategory(MaterialCategory category) {
        // 检查分类是否存在
        MaterialCategory existingCategory = materialCategoryMapper.getCategoryById(category.getId());
        if (existingCategory == null) {
            throw new IllegalArgumentException("分类不存在");
        }
        
        // 检查分类名称是否与其他分类重复
        MaterialCategory categoryWithSameName = materialCategoryMapper.getCategoryByName(category.getName());
        if (categoryWithSameName != null && !categoryWithSameName.getId().equals(category.getId())) {
            throw new IllegalArgumentException("分类名称已存在");
        }
        
        // 如果有父分类，检查父分类是否存在，并防止循环引用
        if (category.getParentId() != null) {
            // 不能将自己设为自己的父分类
            if (category.getId().equals(category.getParentId())) {
                throw new IllegalArgumentException("不能将分类设为自己的父分类");
            }
            
            // 检查父分类是否存在
            MaterialCategory parentCategory = materialCategoryMapper.getCategoryById(category.getParentId());
            if (parentCategory == null) {
                throw new IllegalArgumentException("父分类不存在");
            }
            
            // 防止循环引用：检查父分类的所有上级是否包含当前分类
            Integer currentParentId = parentCategory.getParentId();
            while (currentParentId != null) {
                if (currentParentId.equals(category.getId())) {
                    throw new IllegalArgumentException("不能形成分类的循环引用");
                }
                MaterialCategory currentParent = materialCategoryMapper.getCategoryById(currentParentId);
                if (currentParent == null) {
                    break;
                }
                currentParentId = currentParent.getParentId();
            }
        }
        
        return materialCategoryMapper.updateCategory(category) > 0;
    }

    @Override
    @Transactional
    public boolean deleteCategory(Integer id) {
        // 检查分类是否存在
        MaterialCategory category = materialCategoryMapper.getCategoryById(id);
        if (category == null) {
            throw new IllegalArgumentException("分类不存在");
        }
        
        // 检查是否有子分类
        List<MaterialCategory> subCategories = materialCategoryMapper.getSubCategories(id);
        if (subCategories != null && !subCategories.isEmpty()) {
            throw new IllegalArgumentException("该分类下有子分类，不能直接删除");
        }
        
        // TODO: 检查分类下是否有物资，如果有则不允许删除
        // 这部分需要物资Mapper的支持，暂时省略
        
        return materialCategoryMapper.deleteCategory(id) > 0;
    }

    @Override
    public MaterialCategory getCategoryById(Integer id) {
        return materialCategoryMapper.getCategoryById(id);
    }

    @Override
    public MaterialCategory getCategoryByName(String name) {
        return materialCategoryMapper.getCategoryByName(name);
    }

    @Override
    public List<MaterialCategory> getAllCategories() {
        return materialCategoryMapper.getAllCategories();
    }

    @Override
    public List<MaterialCategory> getCategoryTree() {
        // 获取所有分类
        List<MaterialCategory> allCategories = materialCategoryMapper.getAllCategories();
        
        // 获取顶级分类
        List<MaterialCategory> topCategories = allCategories.stream()
                .filter(category -> category.getParentId() == null)
                .collect(Collectors.toList());
        
        // 递归构建分类树
        return buildCategoryTree(topCategories, allCategories);
    }
    
    /**
     * 递归构建分类树
     * @param parentCategories 父分类列表
     * @param allCategories 所有分类列表
     * @return 分类树
     */
    private List<MaterialCategory> buildCategoryTree(List<MaterialCategory> parentCategories, List<MaterialCategory> allCategories) {
        List<MaterialCategory> result = new ArrayList<>();
        
        for (MaterialCategory parent : parentCategories) {
            // 深拷贝父分类，避免修改原始数据
            MaterialCategory parentCopy = new MaterialCategory();
            parentCopy.setId(parent.getId());
            parentCopy.setName(parent.getName());
            parentCopy.setParentId(parent.getParentId());
            parentCopy.setDescription(parent.getDescription());
            parentCopy.setSortOrder(parent.getSortOrder());
            parentCopy.setCreateTime(parent.getCreateTime());
            parentCopy.setUpdateTime(parent.getUpdateTime());
            
            // 查找当前父分类的所有子分类
            List<MaterialCategory> children = allCategories.stream()
                    .filter(category -> parent.getId().equals(category.getParentId()))
                    .collect(Collectors.toList());
            
            // 如果有子分类，递归构建子分类树
            if (!children.isEmpty()) {
                // 这里可以设置子分类列表，但由于当前实体类没有children字段，
                // 实际应用中可能需要创建一个DTO类来包含children字段
                // parentCopy.setChildren(buildCategoryTree(children, allCategories));
            }
            
            result.add(parentCopy);
        }
        
        return result;
    }

    @Override
    public List<MaterialCategory> getSubCategories(Integer parentId) {
        return materialCategoryMapper.getSubCategories(parentId);
    }
}